/**
 * Created by plmkz520 on 12/8/15.
 */
angular.module('baisonPromotion', ['baisonDb', 'baisonService'])
        .factory('Promotion', ['$rootScope', '$q', 'dbSelect', 'timeStamp2String', function ($rootScope, $q, dbSelect, timeStamp2String) {
                //查找与优惠券中promo_id相关联的促销选项
                var getPromotionOptions_by_promo_id = function (id) {
                    var sql = 'select * from PosPromotionRuleOption where pid="' + id + '"';
                    return dbSelect('YsPos', sql);
                };
                //查找 查找与优惠券中promo_id相关联的促销主表
                var getPromotionRule_by_promo_id = function (id) {
                    var sql = 'select * from PosPromotionRule where is_audit = "1" and is_stop= "0" and promotion_rule_id="' + id + '"';
                    return dbSelect('YsPos', sql);
                };
                //获取促销指定商品列表
                var get_goods_by_promotion = function(pid){
                    var goods_sql = 'select * from PosPromotionRuleGoods where pid=' + pid;
                    return dbSelect('YsPos', goods_sql);
                };

                //检查当前可用促销
                var check_current_prom = function (cur_key, list) {
                    //可用
                    var av_prom_keys = Object.keys(list);
                    if (av_prom_keys.indexOf(cur_key.toString()) == -1) {
                        return false;
                    } else {
                        return true;
                    }
                };
                //获取赠品物品
                var get_gift_goods = function (pid) {
                    var sql = 'select * from PosPromotionRuleGift where pid ="' + pid + '"';
                    return dbSelect('YsPos', sql);
                };

                //添加促销
                var add_available_promotion = function (detail) {

                    var _exists = false;
                    $.each($rootScope.goods_cart.available_promotions, function (i, n) {
                        if (detail['promotion_rule_id'] == n['promotion_rule_id']) {
                            _exists = true;
                        }
                    });
                    //不存在
                    if (!_exists) {

                        $rootScope.goods_cart.available_promotions.push(detail);
                    }
                };

                //获取今日可用促销
                var get_today_promotion = function () {
                    $rootScope.goods_cart.today_promotions = {};

                    var _time = timeStamp2String(0, 'datetime');
                    var _day = timeStamp2String(0, 'day');
                    var _shop_code = $rootScope.current_shop.ShopCode;
                    var _region_code = '';

                    var sql = 'select * from PosPromotionRule where is_audit =1 and is_stop= 0  and begin_time <= "' + _time + '" and end_time >= "' + _time + '"';
                    //TODO 展示用，临时去掉时间条件，IPOS过来的时间为时间戳，未做年月日转换导致无法显示
                    //var sql = 'select * from PosPromotionRule';

                    return dbSelect('YsPos', sql).then(function (ret) {
                        var promiseAll = [];
                        
                        $.each(ret, function (i, n) {

                            var region_list = [];
                            var shop_list = [];

                            var region_sql = 'select rule_region_id from PosPromotionRuleRegion where pid = "' + n.promotion_rule_id + '" and region_code="' + _region_code + '"';

                            promiseAll[i] = dbSelect('YsPos', region_sql).then(function (region_ret) {
                                region_list = region_ret;
                                var shop_sql = 'select rule_shop_id from PosPromotionRuleShop where pid = "' + n.promotion_rule_id + '" and shop_code="' + _shop_code + '"';
                                return dbSelect('YsPos', shop_sql).then(function (shop_ret) {

                                    shop_list = shop_ret;

                                    var deferred = $q.defer();
                                    var promise = deferred.promise;
                                    deferred.resolve('true');
                                    return promise;
                                })
                            }).then(function (ret) {

                                var deferred = $q.defer();
                                var promise = deferred.promise;

                                if (n.is_promotion_day_restrict == 1) {
                                    if (n.promotion_day.indexOf(day) == -1) {
                                        deferred.resolve('false');
                                        return promise;
                                    }
                                }

                                //促销对象控制 只试用VIP 当前没有vip信息
                                if (n.apply_target == 1 && $rootScope.goods_cart.vip.vip_code === '') {
                                    return;
                                }

                                if (n.promotion_shop_type == 1) {

                                    if (n.is_region == 1) {
                                        if (shop_list.length == 0) {
                                            deferred.resolve('false');
                                            return promise;
                                        }
                                    }

                                    //店铺正选
                                    if (n.is_shop == 1) {
                                        if (shop_list.length == 0) {
                                            deferred.resolve('false');
                                            return promise;
                                        }
                                    }

                                    if (n.is_shop == 2) {
                                        if (shop_list.length > 0) {
                                            deferred.resolve('false');
                                            return promise;
                                        }
                                    }
                                }
                                $rootScope.goods_cart.today_promotions[n.promotion_rule_id] = n;


                                deferred.resolve('true');
                                return promise;
                            })
                        });

                        return $q.all(promiseAll);
                    })
                };
                
                //获取促销里是否有可以的促销规则(满钱)(不叠加)
                var get_promotion_options_money = function(promotion,_money){
                	var n = {};
                	var option_info = {};
                	option_info.money = 0;
                	option_info.index = -1;
                    option_info.can_used_num = 0;
					for(var i = 0;i < promotion.options.length;i++){
						n = promotion.options[i];
						if (_money >= n.customer_price){
							if(n.customer_price > option_info.money){
								option_info.money = n.customer_price;
								option_info.index = i;
							}else if(n.customer_price == option_info.money){
                                option_info.money = n.customer_price;
								option_info.index = i;
								if(n.priority < promotion.options[option_info.index].priority){
									option_info.money = n.customer_price;
									option_info.index = i;
								}
							}
                        }
					}
                    //促销条件满足
                    if(option_info.index != -1){
                        option_info.can_used_num = option_info.money >0 ?parseInt(_money/option_info.money):1;
                    }
                    //获取优惠券使用个数
                    if(promotion.is_coupon && $rootScope.goods_cart.couponData[promotion.promotion_rule_id] != undefined){
                        var coupon_num = $rootScope.goods_cart.couponData[promotion.promotion_rule_id].coupon.coupon_code.length;
                        if(option_info.money <= 0){
                            option_info.can_used_num = coupon_num;
                        }else{
                            option_info.can_used_num = (option_info.can_used_num > coupon_num)?coupon_num:option_info.can_used_num;
                        }
                        
                    }
                    //促销叠加开关
                    if(promotion.is_use_more==0 && option_info.index != -1){
                        option_info.can_used_num = 1;
                    }
					return option_info;
                };
                //获取促销里是否有可以的促销规则(满件)(不叠加)
                var get_promotion_options_num = function(promotion,_num){
                	var n = {};
                	var option_info = {};
                	option_info.num = 0;
                	option_info.index = -1;
                    option_info.can_used_num = 0;
					for(var i = 0;i < promotion.options.length;i++){
						n = promotion.options[i];
						if (_num >= n.customer_num){
							if(n.customer_num > option_info.num){
								option_info.num = n.customer_num;
								option_info.index = i;
							}else if(n.customer_num == option_info.num){
                                option_info.num = n.customer_num;
								option_info.index = i;
								if(n.priority < promotion.options[option_info.index].priority){
									option_info.num = n.customer_num;
									option_info.index = i;
								}
							}
                        }
					}
                     //促销条件满足
                    if(option_info.index != -1){
                        option_info.can_used_num = option_info.num > 0?parseInt(_num/option_info.num):1;
                    }
                    //获取优惠券使用个数
                    if(promotion.is_coupon && $rootScope.goods_cart.couponData[promotion.promotion_rule_id] != undefined){
                        var coupon_num = $rootScope.goods_cart.couponData[promotion.promotion_rule_id].coupon.coupon_code.length;
                        
                        if(option_info.num <= 0){
                            option_info.can_used_num = coupon_num;
                        }else{
                            option_info.can_used_num = (option_info.can_used_num > coupon_num)?coupon_num:option_info.can_used_num;
                        }
                        
                    }
                    //促销叠加开关
                    if(!promotion.is_use_more==0 && option_info.index != -1){
                        option_info.can_used_num = 1;
                    }
					return option_info;
                };
                //获取可用促销逻辑
                var get_available_promotion_by_list = function (n, isUse, goods_sku_list_key) {
                    
                    var _money = 0; //总金额
                    var _num = 0; //数量
                    var index = -1; 
                    var _promotion_goods = [];
                    var option_info = {};
                	option_info.money = 0;
                    option_info.num = 0;
                	option_info.index = -1;
                    option_info.can_used_num = 0;
                    //指定范围商品
                    if (n.promotion_goods_type == 1) {

                        ////循环购物车里面的

                        $.each($rootScope.goods_cart.list, function (key, val) {

                            var index = goods_sku_list_key.indexOf(val.SkuCode);//$.inArray(val.SkuCode, goods_sku_list_key);
                            if (index != -1 ) { //&& val.promotionid == undefined

                                switch (parseInt(n.promotion_type)) {
                                    case 0: //满额立减
                                    case 1: //满额赠件
                                    case 4: //满额打折
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //获取使用的优惠券
                                            $.each($rootScope.goods_cart.couponData, function (i, v) {
                                                if (v.coupon.promo_id == n.promotion_rule_id) {
                                                    _money = _money + parseFloat(val.money);
                                                }
                                            });
                                        } else {
                                            _money = _money + parseFloat(val.money);
                                        }

                                        break;
                                    case 2: //满件减钱
                                    case 3: //满件赠件  
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //TODO 获取使用的优惠券

                                            $.each($rootScope.goods_cart.couponData, function (i, v) {

                                                if (v.coupon.promo_id == n.promotion_rule_id) {

                                                    _num = _num + parseFloat(val.num);
                                                }
                                            });
                                        } else {
                                            _num = _num + parseFloat(val.num);
                                        }

                                        break;
                                    case 5:
                                        //套组
                                        break;
                                    case 6:
                                        //积分
                                        break;
                                }
                            }
                        });
                        switch (parseInt(n.promotion_type)) {
                            case 0: //满额立减
                            case 1: //满额赠件
                            case 4: //满额打折 
								option_info = get_promotion_options_money(n,_money);
                                break;
                            case 2: //满件减钱
                            case 3: //满件赠件
								option_info = get_promotion_options_num(n,_num);
                                break;
                            case 5:
                                //套组
                                option_info.index = 0;
                                option_info.can_used_num = 1;
                                break;
                            case 6:
                                //积分
                                break;
                        }
                    } else {
                        //促销策略中没有指定商品
                        //console.log()
                        $.each($rootScope.goods_cart.list, function (key, val) {
                            //if (val.promotionid == undefined) {
                                switch (parseInt(n.promotion_type)) {
                                    case 0: //满额立减
                                    case 1: //满额赠件
                                    case 4: //满额打折 
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //获取使用的优惠券
                                            $.each($rootScope.goods_cart.couponData, function (i, v) {
                                                if (v.coupon.promo_id == n.promotion_rule_id) {
                                                    _money = _money + parseFloat(val.money);
                                                }
                                            });
                                        } else {
                                            _money = _money + parseFloat(val.money);
                                        }
                                        break;
                                    case 2: //满件减钱
                                    case 3: //满件赠件    
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //TODO 获取使用的优惠券

                                            $.each($rootScope.goods_cart.couponData, function (i, v) {
                                                if (v.coupon.promo_id == n.promotion_rule_id) {
                                                    _num = _num + parseFloat(val.num);
                                                }
                                            });
                                        } else {

                                            _num = _num + parseFloat(val.num);
                                        }

                                        break;
                                    case 5:
                                        //套组
                                        break;
                                    case 6:
                                        //积分
                                        break;
                                }
                           // }


                        });
                        switch (parseInt(n.promotion_type)) {
                            case 0: //满额立减
                            case 1: //满额赠件
                            case 4: //满额打折 
								option_info = get_promotion_options_money(n,_money);
                                break;
                            case 2: //满件减钱
                            case 3: //满件赠件   
								option_info = get_promotion_options_num(n,_num);
                                break;
                            case 5:
                                //套组
                                
                                option_info.index = 0;
                                option_info.can_used_num = 1;
                                //console.log(JSON.stringify(n));
                                break;
                            case 6:
                                //积分
                                break;
                        }
                    }
                    
                    return option_info;
                };
                //获取可用促销
                var get_available_promotion = function () {
                    return get_today_promotion().then(function (ret) {
                        if (Object.keys($rootScope.goods_cart.today_promotions).length == 0) {
                            return;
                        }

                        $rootScope.goods_cart.available_promotions = {};
                        $rootScope.goods_cart.promotion_goods = {};

                        var promiseAll = [];

                        $.each($rootScope.goods_cart.today_promotions, function (i, n) {

                            var option_list = [];
                            var category_list = [];
                            var goods_list = [];
                            var goods_sku_list_key = [];
                            var isUse = false;//是否成功使用促销
                            var index = -1;
                            var _promotion_goods = [];//促销商品

                            //baison_app.api.alert({msg:$rootScope.goods_cart.share_promotion_id});

                            var option_sql = 'select * from PosPromotionRuleOption where pid = ' + n.promotion_rule_id;
                            //if($rootScope.goods_cart.vip.vip_code !== ''){
                            //	option_sql += ' and vip_price <= '  + $rootScope.goods_cart.info.total_money+' order by vip_price DESC limit 1';
                            //}else{ //顾客整单金额
                            //	option_sql += ' and customer_price <= '+$rootScope.goods_cart.info.total_money+ ' order by customer_price DESC limit 1';
                            //}
                            promiseAll[i] = dbSelect('YsPos', option_sql).then(function (option_ret) {
                                option_list = option_ret;
                                var category_sql = 'select * from PosPromotionRuleCategory where pid=' + n.promotion_rule_id;
                                return dbSelect('YsPos', category_sql).then(function (category_ret) {
                                    category_list = category_ret;

                                    var deferred = $q.defer();
                                    var promise = deferred.promise;
                                    deferred.resolve('true');
                                    return promise;
                                })
                            }).then(function (ret) {
                                var goods_sql = 'select * from PosPromotionRuleGoods where pid=' + n.promotion_rule_id;
                                //baison_app.api.alert({msg:goods_sql});
                                return dbSelect('YsPos', goods_sql).then(function (goods_ret) {
                                    $.each(goods_ret, function (_g_k, _g_v) {
                                        goods_sku_list_key.push(_g_v.sku);
                                    });

                                    goods_list = goods_ret;
                                    var deferred = $q.defer();
                                    var promise = deferred.promise;
                                    deferred.resolve('true');
                                    return promise;
                                })
                            }).then(function (ret) {

                                var deferred = $q.defer();
                                var promise = deferred.promise;

                                //选择促销内已有独享的，不能重复选择独享
                                if ($rootScope.goods_cart.share_promotion_id > 0) {
                                    if (n.is_share == 1 && $rootScope.goods_cart.share_promotion_id != n.promotion_rule_id) {
                                        deferred.resolve('false');
                                        return promise;
                                    }
                                }

                                var _promotion = n;
                                _promotion.options = option_list;
                                 //可用促销规则信息
                                var option_info = {};

                                //购物车中有商品
                                if ($rootScope.goods_cart.list.length > 0) {

                                    if (_promotion.is_stop == 0) {
                                        if (n.promotion_goods_type == 1) {
                                            if (n.is_category == 1) {
                                                if (category_list.length == 0) {
                                                    deferred.resolve('false');
                                                    return promise;
                                                }
                                            }
                                            if (n.is_goods > 0) {
                                                if (goods_list.length == 0) {
                                                    deferred.resolve('false');
                                                    return promise;
                                                }
                                            }
                                        }
                                        option_info = get_available_promotion_by_list(_promotion, isUse, goods_sku_list_key);
                                    }

                                }
                                else {
                                    if (_promotion.is_stop == 0) {
                                        _promotion.goods_list = goods_sku_list_key;
                                        isUse = true;
                                    }
                                }
                                
								if(option_info.index != -1 && option_info.index != undefined){
									_promotion.reduce_price = option_list[option_info.index].reduce_price;
				                    _promotion.gift_total_price = option_list[option_info.index].gift_total_price;
				                    _promotion.gift_total_num = option_list[option_info.index].gift_total_num;
				                    _promotion.rebate = option_list[option_info.index].rebate;
				                    _promotion.customer_price = option_list[option_info.index].customer_price;
				                    _promotion.customer_num = option_list[option_info.index].customer_num;
				                    _promotion.vip_price = option_list[option_info.index].vip_price;
                                    _promotion.goods_list = goods_sku_list_key;
                                    _promotion.can_used_num = option_info.can_used_num;
                                   
				                    isUse = true;
								}
                                if (isUse) {

                                    $rootScope.goods_cart.available_promotions[n.promotion_rule_id] = _promotion;

                                }
                                deferred.resolve('true');
                                return promise;
                            });
                        });
                       
                        return $q.all(promiseAll);
                    })
                };
                var list = function () {
                    return get_today_promotion();
                };

                return {
                    list: list,
                    check_current_prom: check_current_prom,
                    get_gift_goods: get_gift_goods,
                    get_today_promotion: get_today_promotion,
                    get_available_promotion: get_available_promotion,
                    getPromotionOptions_by_promo_id: getPromotionOptions_by_promo_id,
                    getPromotionRule_by_promo_id: getPromotionRule_by_promo_id,
                    get_goods_by_promotion:get_goods_by_promotion

                };
            }])
        ;